package com.example.kuaizu.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

@Configuration
public class EmailConfig {

    private static final Logger log = LoggerFactory.getLogger(EmailConfig.class);
    // 配置常量
    @Value("${email.smtp-host}")
    private String SMTP_HOST;//或"smtp.qq.com"
    @Value("${email.smtp-port}")
    private int SMTP_PORT = 465;//或465
    @Value("${email.smtp-name}")
    private String USER_NAME;//发件人邮箱地址
    @Value("${email.smtp-password}")
    private String PASSWORD;//发件人邮箱密码

    @Bean
    public String getUSER_NAME() {
        return USER_NAME;
    }

    //配置对应的信息
    @Bean("emailProPerties")
    public Properties setEmailInfo() {
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        // 表示 SMTP 发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");// 开启认证
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.ssl.enable", "true"); // 启用 SSL
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.fallback", "false");
        // 添加连接超时和读取超时设置
        props.put("mail.smtp.connectiontimeout", "5000"); // 连接超时 5 秒
        props.put("mail.smtp.timeout", "5000"); // 读取超时 5 秒
        props.put("mail.smtp.from", USER_NAME);    // mailfrom 参数
        props.put("mail.user", USER_NAME);// 发件人的账号（在控制台创建的发信地址）
        props.put("mail.password", PASSWORD);// 发信地址的 smtp 密码（在控制台选择发信地址进行设置）
        System.setProperty("mail.mime.splitlongparameters", "false");// 用于解决附件名过长导致的显示异常
        return props;
    }

    //构建对应的授权信息
    @Bean
    public Authenticator getAuthenticator() {
        // 构建授权信息，用于进行 SMTP 进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                return new PasswordAuthentication(USER_NAME, PASSWORD);
            }
        };
        return authenticator;
    }
}
